package at.fhj.pse.domain.impl;

import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Logger;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.inject.Inject;

import at.fhj.pse.datasource.EmployeeDAO;
import at.fhj.pse.datasource.exception.DatasourceLayerException;
import at.fhj.pse.datasource.model.Employee;
import at.fhj.pse.domain.EmployeeBean;
import at.fhj.pse.domain.exception.DomainLayerException;
import at.fhj.pse.domain.exception.StacktraceToString;
import at.fhj.pse.domain.exception.WrongCredentialsException;

@Stateless
@Local(EmployeeBean.class)
public class EmployeeBeanImpl implements Serializable, EmployeeBean {

	private static final long serialVersionUID = 2464734774973478451L;

	private final Logger LOG = Logger
			.getLogger(EmployeeBeanImpl.class.getName());
	
	@Inject
	private EmployeeDAO employeeDao;

	@Override
	public Employee getEmployeeById(long id) {
		return this.employeeDao.getEmployeeById(id);
	}

	@Override
	public Employee login(String username, String password) throws IOException, WrongCredentialsException {
		if (username == null) {
			throw new DomainLayerException("username is null", new IllegalArgumentException());
		}
		if (password == null) {
			throw new DomainLayerException("password is null", new IllegalArgumentException());
		}
		try {
			Employee employee = employeeDao.checkLogin(username, password);
			if (employee != null)
				return employee;
			else
				return null;
		} catch (NullPointerException ex) {
			DomainLayerException e = new DomainLayerException("employeeDao is null", ex);
			LOG.warning(e.getMessage());
			LOG.warning(StacktraceToString.build(e));
			throw e;
		} catch (DatasourceLayerException ex) {
			throw new WrongCredentialsException(ex.getMessage(), ex);
		}
	}
}